package com.school.base.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;

import com.school.base.dao.INewsDao;
import com.school.base.model.News;
import com.school.common.base.BaseDao;
import com.school.common.util.MapUtils;

public class NewsDao extends BaseDao implements INewsDao {

	@Override
	public News getNewsById(int id) {
		return (News) this.getObjectById(News.class, id);
	}

	private String getExpressSql(News news, List express) {
		String sql = "";
		if (news != null) {
			if (news.getTitle() != null && !news.getTitle().isEmpty()) {

				sql += " and n.title like ?";
				express.add("%" + news.getTitle() + "%");
			}
		}
		return sql;
	}

	@Override
	public List<News> getNewsList(News news, int offset, int pageSize) {
		String sql = "select n.*,a.real_name creatorName from b_news n left join b_admin a on a.id=n.creator_id where 1=1 ";
		List express = new ArrayList();
		sql += this.getExpressSql(news, express);
		sql += " order by n.sticky desc,n.create_time desc";
		SQLQuery query = this.getCurrentSession().createSQLQuery(sql);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		if (express != null) {
			for (int i = 0; i < express.size(); i++) {
				query.setParameter(i, express.get(i));
			}
		}
		query.setMaxResults(pageSize);
		query.setFirstResult(offset);
		List list = query.list();
		List<News> newsList = new ArrayList<News>();
		for (Object obj : list) {
			News n = (News) MapUtils.mapToBean((HashMap<String, Object>) obj, News.class);
			newsList.add(n);
		}
		return newsList;
	}

	@Override
	public int getTotalCount(News news) {
		String sql = "select count(*) from b_news n left join b_admin a on a.id=n.creator_id where 1=1 ";
		List express = new ArrayList();
		sql += this.getExpressSql(news, express);
		return this.getRecordCountBySql(sql, express);
	}

	@Override
	public void updateNews(News news) {
		String hql = "update News set title=?,content=?,sticky=? where id=?";
		List express = new ArrayList();
		express.add(news.getTitle());
		express.add(news.getContent());
		express.add(news.getSticky());
		express.add(news.getId());
		this.executeHql(hql, express);
	}

	@Override
	public void deleteNews(int id) {
		News news = new News();
		news.setId(id);
		this.delete(news);
	}

	@Override
	public void insertNews(News news) {
		this.insert(news);
	}

	@Override
	public void updateNewsSticky(int newsId, int to) {
		String hql = "update News set sticky=? where id=?";
		List express = new ArrayList();
		express.add(to);
		express.add(newsId);
		this.executeHql(hql, express);
	}

}
